/* Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */

/** @file
 *
 * @defgroup ble_sdk_uart_over_ble_main main.c
 * @{
 * @ingroup  ble_sdk_app_nus_eval
 * @brief    UART over BLE application main file.
 *
 * This file contains the source code for a sample application that uses the Nordic UART service.
 * This application uses the @ref srvlib_conn_params module.
 */

#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "nrf51_bitfields.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_bas.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "app_button.h"
#include "ble_nus.h"
#include "app_uart.h"
#include "app_util_platform.h"
#include "bsp.h"
#include "bsp_btn_ble.h"
#include "nrf_delay.h"

#include "ble_wechat_service.h"

#include "board_support.h"
#include "hal_dmp.h"
//#include "user_fifo.h"

#include "data_manage.h"

#include "MX25_CMD.h"
#include "log.h"

#include "mpbledemo2.h"
#include "config.h"
#include "lb_batt.h"

ble_nus_t                               m_nus;                                      /**< Structure to identify the Nordic UART Service. */
uint16_t                         		m_conn_handle = BLE_CONN_HANDLE_INVALID;    /**< Handle of the current connection. */

#if defined(DEVICE_PWM)
static ble_uuid_t                       m_adv_uuids[] = {{BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}};  /**< Universally unique service identifier. */
#endif


uint8_t	 								m_addl_adv_manuf_data[BLE_GAP_ADDR_LEN];

ble_wechat_t 							m_ble_wechat;

extern ble_bas_t                        m_bas;

extern data_handler *m_mpbledemo2_handler;


/**@brief Function for assert macro callback.
 *
 * @details This function will be called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and does not fit a final product. You need to analyse 
 *          how your product is supposed to react in case of Assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num    Line number of the failing ASSERT call.
 * @param[in] p_file_name File name of the failing ASSERT call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(DEAD_BEEF, line_num, p_file_name);
}


/**@brief Function for the GAP initialization.
 *
 * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of 
 *          the device. It also sets the permissions and appearance.
 */
static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
    
    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *) DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}

void run_self_test(void);
void set_test_flag(bool value);

extern uint16_t step;
/**@brief Function for handling the data from the Nordic UART Service.
 *
 * @details This function will process the data received from the Nordic UART BLE Service and send
 *          it to the UART module.
 *
 * @param[in] p_nus    Nordic UART Service structure.
 * @param[in] p_data   Data to be send to UART module.
 * @param[in] length   Length of the data.
 */
/**@snippet [Handling the data received over BLE] */
static void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data, uint16_t length)
{
//    for (uint32_t i = 0; i < length; i++)
//    {
//        while(app_uart_put(p_data[i]) != NRF_SUCCESS);
//    }
//    while(app_uart_put('\n') != NRF_SUCCESS);
    uint8_t cmd = *p_data;
    
    switch (cmd)
    {
        case 't':
			set_test_flag(true);
//            set_test_flag(true);
            //run_self_test();
            break;
        case '1':
			step = 0;
            break;
        case '2':
            break;
        default:
            break;
    }
    
}
/**@snippet [Handling the data received over BLE] */


/**@brief Function for initializing services that will be used by the application.
 */
static void services_init(void)
{
    uint32_t       err_code;
    ble_nus_init_t nus_init;
    
    memset(&nus_init, 0, sizeof(nus_init));

    nus_init.data_handler = nus_data_handler;
    
    err_code = ble_nus_init(&m_nus, &nus_init);
    APP_ERROR_CHECK(err_code);
	
	err_code = ble_wechat_service_init(&m_ble_wechat);
	APP_ERROR_CHECK(err_code);
	
	init_bat_service();
}


/**@brief Function for handling an event from the Connection Parameters Module.
 *
 * @details This function will be called for all events in the Connection Parameters Module
 *          which are passed to the application.
 *
 * @note All this function does is to disconnect. This could have been done by simply setting
 *       the disconnect_on_fail config parameter, but instead we use the event handler
 *       mechanism to demonstrate its use.
 *
 * @param[in] p_evt  Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    uint32_t err_code;
    
    if(p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for handling errors from the Connection Parameters module.
 *
 * @param[in] nrf_error  Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    uint32_t               err_code;
    ble_conn_params_init_t cp_init;
    
    memset(&cp_init, 0, sizeof(cp_init));

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    cp_init.error_handler                  = conn_params_error_handler;
    
    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}


void sensor_pwd_down(void);
/**@brief Function for putting the chip into sleep mode.
 *
 * @note This function will not return.
 */
static void sleep_mode_enter(void)
{
    uint32_t err_code = bsp_indication_set(BSP_INDICATE_IDLE);
    APP_ERROR_CHECK(err_code);

    // Prepare wakeup buttons.
    err_code = bsp_btn_ble_sleep_mode_prepare();
    APP_ERROR_CHECK(err_code);
	
	// Sensor
	sensor_pwd_down();

    // Go to system-off mode (this function will not return; wakeup will cause a reset).
//    err_code = sd_power_system_off();
//    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling advertising events.
 *
 * @details This function will be called for advertising events which are passed to the application.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;

    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
            err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
            APP_ERROR_CHECK(err_code);
            break;
        case BLE_ADV_EVT_IDLE:
            sleep_mode_enter();
            break;
        default:
            break;
    }
}


/**@brief Function for the Application's S110 SoftDevice event handler.
 *
 * @param[in] p_ble_evt S110 SoftDevice event.
 */
static void on_ble_evt(ble_evt_t * p_ble_evt)
{
    uint32_t                         err_code;
    ble_gap_conn_params_t p_conn_params;
    
    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
            APP_ERROR_CHECK(err_code);
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
            
            err_code = sd_ble_gap_ppcp_get(&p_conn_params);
            APP_ERROR_CHECK(err_code);
			LOG_X("Connect");
            LOG_X("max:%d,min:%d,latency:%d,timeout:%d", (int)(p_conn_params.max_conn_interval*1.25), (int)(p_conn_params.min_conn_interval*1.25),
                                                        p_conn_params.slave_latency, p_conn_params.conn_sup_timeout*10);
        
            break;
            
        case BLE_GAP_EVT_DISCONNECTED:
            err_code = bsp_indication_set(BSP_INDICATE_IDLE);
            APP_ERROR_CHECK(err_code);
			LOG_X("Disconnect");
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;

        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            // Pairing not supported
            err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
            // No system attributes have been stored.
            err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
            APP_ERROR_CHECK(err_code);
            break;
        
        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
            LOG_X("BLE_GAP_EVT_CONN_PARAM_UPDATE");
        
            err_code = sd_ble_gap_ppcp_get(&p_conn_params);
            APP_ERROR_CHECK(err_code);
            LOG_X("max:%d,min:%d,latency:%d,timeout:%d", (int)(p_conn_params.max_conn_interval*1.25), (int)(p_conn_params.min_conn_interval*1.25),
                                                        p_conn_params.slave_latency, p_conn_params.conn_sup_timeout*10);
            break;
			
		case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
		{
			LOG_X("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST");
			break;
		}
		
		case NRF_EVT_FLASH_OPERATION_SUCCESS:
		{
			LOG_X("NRF_EVT_FLASH_OPERATION_SUCCESS");
			break;
		}
		
		case NRF_EVT_FLASH_OPERATION_ERROR:
		{
			LOG_X("NRF_EVT_FLASH_OPERATION_ERROR");
			break;
		}
			

        default:
            // No implementation needed.
            break;
    }
}


/**@brief Function for dispatching a S110 SoftDevice event to all modules with a S110 SoftDevice 
 *        event handler.
 *
 * @details This function is called from the S110 SoftDevice event interrupt handler after a S110 
 *          SoftDevice event has been received.
 *
 * @param[in] p_ble_evt  S110 SoftDevice event.
 */
static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
    ble_conn_params_on_ble_evt(p_ble_evt);
    ble_nus_on_ble_evt(&m_nus, p_ble_evt);
    on_ble_evt(p_ble_evt);
    ble_advertising_on_ble_evt(p_ble_evt);
    bsp_btn_ble_on_ble_evt(p_ble_evt);
    ble_wechat_on_ble_evt(&m_ble_wechat, p_ble_evt, m_mpbledemo2_handler);
	m_mpbledemo2_handler->m_data_on_ble_evt_func(&m_ble_wechat,p_ble_evt);
	ble_bas_on_ble_evt(&m_bas, p_ble_evt);
}


/**@brief Function for the S110 SoftDevice initialization.
 *
 * @details This function initializes the S110 SoftDevice and the BLE event interrupt.
 */
static void ble_stack_init(void)
{
    uint32_t err_code;
    
    // Initialize SoftDevice.
    SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, NULL);

    // Enable BLE stack.
    ble_enable_params_t ble_enable_params;
    memset(&ble_enable_params, 0, sizeof(ble_enable_params));
#ifdef S130
    ble_enable_params.gatts_enable_params.attr_tab_size   = BLE_GATTS_ATTR_TAB_SIZE_DEFAULT;
#endif
    ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT;
    err_code = sd_ble_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);
    
    // Subscribe for BLE events.
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}

void set_test_flag(bool flag);

/**@brief Function for handling events from the BSP module.
 *
 * @param[in]   event   Event generated by button press.
 */
void bsp_event_handler(bsp_event_t event)
{
    uint32_t err_code;
    switch (event)
    {
        case BSP_EVENT_SLEEP:
			LOG_X("BSP_EVENT_SLEEP");
            sleep_mode_enter();
            break;

        case BSP_EVENT_DISCONNECT:
            err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BSP_EVENT_WHITELIST_OFF:
            err_code = ble_advertising_restart_without_whitelist();
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

		case BSP_EVENT_KEY_2:
		{
//			uint32_t err_code;
//			err_code = m_mpbledemo2_handler->m_data_button_handler_func(&m_ble_wechat, 3);
//			APP_ERROR_CHECK(err_code);
			
			//gyro_data_ready_cb();
			//sleep_mode_enter();

			LOG_X("User key pushed");
			
//			set_start_flag(true);
			
			break;
		}
		
		
		case BSP_EVENT_KEY_0:
            //bsp_indication_set(BSP_INDICATE_CHAGING);
        
            LOG_X("Charging");
            break;
        
        case BSP_EVENT_KEY_1:
            LOG_X("Charger connected");
            break;
        
        case BSP_EVENT_RELEASE_KEY_0:
            LOG_X("Charge complete");
            //bsp_indication_set(BSP_INDICATE_CHAGE_COMPLETE);
            break;
        
        case BSP_EVENT_RELEASE_KEY_1:
            LOG_X("Charger disconnected");
            break;
        
        case BSP_EVENT_RELEASE_KEY_2:
            //sleep_mode_enter();
            LOG_X("BSP_EVENT_RELEASE_KEY_2");
            break;
		
		case BSP_EVENT_KEY_3:
		{
			LOG_X("MPU INT");
			gyro_data_ready_cb();
			break;
		}
		
		case BSP_EVENT_RELEASE_KEY_3:
		{
			LOG_X("MPU INT release");
			break;
		}
			
        default:
            break;
    }
}

// Functions below are in file hal_dmp.c
void set_test_flag(bool flag);
void send_data_timer_start(void);
void led_status_timer_start(uint16_t ms);
void handle_input(char cmd);

/**@brief   Function for handling app_uart events.
 *
 * @details This function will receive a single character from the app_uart module and append it to 
 *          a string. The string will be be sent over BLE when the last character received was a 
 *          'new line' i.e '\n' (hex 0x0D) or if the string has reached a length of 
 *          @ref NUS_MAX_DATA_LENGTH.
 */
/**@snippet [Handling the data received over UART] */
void uart_event_handle(app_uart_evt_t * p_event)
{
    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
    static uint8_t index = 0;
//    uint32_t       err_code;

    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
            UNUSED_VARIABLE(app_uart_get(&data_array[index]));
            index++;

            //if ((data_array[index - 1] == '\n') || (index >= (BLE_NUS_MAX_DATA_LEN)))
            if (data_array[index - 1] == '\n')
            {
                handle_input(data_array[index - 2]);
                
                //printf("select: %d\r\n", data_array[index - 2]);
                
                //err_code = ble_nus_string_send(&m_nus, data_array, index);
//                if (err_code != NRF_ERROR_INVALID_STATE)
//                {
//                    APP_ERROR_CHECK(err_code);
//                }
                
                index = 0;
            }
            break;

        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_communication);
            break;

        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;

        default:
            break;
    }
}
/**@snippet [Handling the data received over UART] */


/**@brief  Function for initializing the UART module.
 */
/**@snippet [UART Initialization] */
static void uart_init(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud250000
    };

    APP_UART_FIFO_INIT( &comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);
    APP_ERROR_CHECK(err_code);
}
/**@snippet [UART Initialization] */


//function for register all products
void register_all_products(void)
{
    REGISTER(mpbledemo2);
}

void data_handler_init(data_handler** p_data_handler, uint8_t product_type)
{
    if (*p_data_handler == NULL)
    {
        *p_data_handler = get_handler_by_type(product_type);
    }
}


void get_mac_addr(uint8_t *p_mac_addr)
{
    uint32_t error_code;
    ble_gap_addr_t *p_mac_addr_t = (ble_gap_addr_t*)malloc(sizeof(ble_gap_addr_t));
    error_code = sd_ble_gap_address_get(p_mac_addr_t);
    APP_ERROR_CHECK(error_code);
#ifdef CATCH_LOG
//    printf("\r\n error:%d",error_code);
    printf("\r\n get mac addr");
#endif
    uint8_t *d = p_mac_addr_t->addr;
    for ( uint8_t i = 6; i >0;)
    {
        i--;
        p_mac_addr[5-i]= d[i];
#ifdef CATCH_LOG
        printf ( ":%02x", d[i]);
#endif
    }
#ifdef CATCH_LOG
    putchar ( '\n' );
#endif
    free(p_mac_addr_t);
    p_mac_addr_t = NULL;
}

/**@brief Function for initializing the Advertising functionality.
 */
static void advertising_init(void)
{
	#if !defined(DEVICE_PWM)
    uint32_t      err_code;
    ble_advdata_t advdata;
//    ble_advdata_t scanrsp;
	
	ble_advdata_manuf_data_t        manuf_data;
	
	ble_uuid_t adv_uuids[] =
    {
        {BLE_UUID_WECHAT_SERVICE,BLE_UUID_TYPE_BLE}
    };

    // Build advertising data struct to pass into @ref ble_advertising_init.
    memset(&advdata, 0, sizeof(advdata));
    advdata.name_type          = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance = false;
    advdata.flags              = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;

    advdata.uuids_complete.uuid_cnt = sizeof(adv_uuids) / sizeof(adv_uuids[0]);
    advdata.uuids_complete.p_uuids  = adv_uuids;
	
    manuf_data.company_identifier = COMPANY_IDENTIFIER;
    manuf_data.data.size          = sizeof(m_addl_adv_manuf_data);
    manuf_data.data.p_data        = m_addl_adv_manuf_data;
    advdata.p_manuf_specific_data = &manuf_data;
	
	
//    memset(&scanrsp, 0, sizeof(scanrsp));
//    advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
//    advdata.uuids_complete.p_uuids  = m_adv_uuids;

    ble_adv_modes_config_t options = {0};
    options.ble_adv_fast_enabled  = BLE_ADV_FAST_ENABLED;
    options.ble_adv_fast_interval = APP_ADV_INTERVAL;
    options.ble_adv_fast_timeout  = APP_ADV_TIMEOUT_IN_SECONDS;

	options.ble_adv_slow_enabled = BLE_ADV_SLOW_ENABLED;
    options.ble_adv_slow_interval = APP_ADV_INTERVAL_SLOW;
	
    err_code = ble_advertising_init(&advdata, NULL, &options, on_adv_evt, NULL);
    APP_ERROR_CHECK(err_code);
	#else
	
	uint32_t      err_code;
    ble_advdata_t advdata;
    ble_advdata_t scanrsp;

    // Build advertising data struct to pass into @ref ble_advertising_init.
    memset(&advdata, 0, sizeof(advdata));
    advdata.name_type          = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance = true;
    advdata.flags              = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;

    memset(&scanrsp, 0, sizeof(scanrsp));
    advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
    advdata.uuids_complete.p_uuids  = m_adv_uuids;

    ble_adv_modes_config_t options = {0};
    options.ble_adv_fast_enabled  = BLE_ADV_FAST_ENABLED;
    options.ble_adv_fast_interval = APP_ADV_INTERVAL;
    options.ble_adv_fast_timeout  = APP_ADV_TIMEOUT_IN_SECONDS;

	options.ble_adv_slow_enabled = BLE_ADV_SLOW_ENABLED;
    options.ble_adv_slow_interval = APP_ADV_INTERVAL_SLOW;
	
    err_code = ble_advertising_init(&advdata, NULL, &options, on_adv_evt, NULL);
    APP_ERROR_CHECK(err_code);
	
	#endif
}
	

/**@brief Function for initializing buttons and leds.
 *
 * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
 */
static void buttons_leds_init(bool * p_erase_bonds)
{
    bsp_event_t startup_event;

    uint32_t err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS,
                                 APP_TIMER_TICKS(100, APP_TIMER_PRESCALER), 
                                 bsp_event_handler);
    APP_ERROR_CHECK(err_code);

    err_code = bsp_btn_ble_init(NULL, &startup_event);
    APP_ERROR_CHECK(err_code);

    *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
}


/**@brief Function for placing the application in low power state while waiting for events.
 */
static void power_manage(void)
{
    uint32_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}

static void other_gpio_config(void)
{
	nrf_gpio_cfg_input(1, GPIO_PIN_CNF_PULL_Disabled);   // ADC in
	nrf_gpio_cfg_input(13, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(17, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(20, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(21, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(22, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(23, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(24, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(25, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(28, GPIO_PIN_CNF_PULL_Disabled); 
	nrf_gpio_cfg_input(29, GPIO_PIN_CNF_PULL_Disabled); 
	
}


/**@brief Application main function.
 */
int main(void)
{
    uint32_t err_code;
    bool erase_bonds;
    uint8_t  start_string[] = START_STRING;

    // Initialize.
    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_MAX_TIMERS, APP_TIMER_OP_QUEUE_SIZE, false);
	
    #if defined(DEBUG_LOG) || defined(CATCH_LOG)
	uart_init();
	#endif
	
	other_gpio_config();
	
    buttons_leds_init(&erase_bonds);
    
    //Initial_Spi();

    ble_stack_init();
	
	get_mac_addr(m_addl_adv_manuf_data);		// get mac addr
    register_all_products();
#ifdef CATCH_LOG
    printf(" register products!\r\n");
#endif

    data_handler_init(&m_mpbledemo2_handler,	PRODUCT_TYPE_MPBLEDEMO2);
#ifdef CATCH_LOG
    printf(" data handler init!\r\n");
#endif

	APP_ERROR_CHECK(m_mpbledemo2_handler->m_data_init_func());
#ifdef CATCH_LOG
    printf(" mpbledemo2 init\r\n");
#endif
	
    board_init();

	save_app_type(9);	// only for test 20160901, remeber comment this after tape over

	load_app_type();
	
    hal_dmp_init();
	
	load_data();        	/*  Load saved bias form flash */
    load_data_out_mode();   /*  Load data out mode from flash */
	
    gap_params_init();
    services_init();
    advertising_init();
    conn_params_init();
    
    LOG_X("%s\r\n",start_string);
	if(get_data_out_mode() == DATA_FOR_ANO)
    {
        LOG_X("Data for ANO!");
    }
    else
    {
        LOG_X("Data for Collection!");
    }

    err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    APP_ERROR_CHECK(err_code);
    
	check_charger();
    // Enter main loop.
    for (;;)
    {
        get_data();
		check_charger();
        power_manage();
		m_mpbledemo2_handler->m_data_main_process_func(&m_ble_wechat);
    }
}

void HardFault_Handler(void)
{
    LOG_X("HardFault_Handler");
	
	
//    while(1)
//    {
//		for(uint8_t i = 0; i < 30; i++)
//		{
//			nrf_gpio_pin_clear(7);
//			nrf_gpio_pin_clear(8);
//			nrf_delay_ms(400);
//			
//			nrf_gpio_pin_set(7);
//			nrf_gpio_pin_set(8);
//			nrf_delay_ms(400);
//		}
//		break;
//    }
	
	NVIC_SystemReset();
}


/** 
 * @}
 */
